package com.itany.websocket.websocket.controller;

import com.itany.websocket.websocket.websocket.TalkWebSocketHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/login")
    public String login(String nickname, HttpSession session) throws IOException {
        System.out.println("UserController.login()");

        System.out.println("nickname = " + nickname);

        session.setAttribute("nickname",nickname);

        Map<String, WebSocketSession> users= TalkWebSocketHandler.users;

        for (Map.Entry<String,WebSocketSession> userEntry : users.entrySet()) {
            synchronized ("abc") {
                if(userEntry.getValue().isOpen()){
                    //服务器向客户端推送消息
                    userEntry.getValue().sendMessage(new TextMessage(nickname+"进入聊天室 "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                }
            }
        }

        return "talk";
    }
}
